<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
</html>
<script>
  const treeData = [
    {
      id: "1",
      name: "Node 1",
      children: [
        {
          id: "1-1",
          name: "Child Node 1-1",
          children: [
            { id: "1-1-1", name: "Child Node 1-1-1" },
            { id: "1-1-2", name: "Child Node 1-1-2" },
          ],
        },
        {
          id: "1-2",
          name: "Child Node 1-2",
          children: [{ id: "1-2-1", name: "Child Node 1-2-1" }],
        },
      ],
    },
    {
      id: "2",
      name: "Node 2",
      children: [{ id: "2-1", name: "Child Node 2-1" }],
    },
  ];

  function findNodeAndDescendantsById(treeData, id) {
    for (const node of treeData) {
      if (node.id === id) {
        return collectDescendants(node); // 找到目标节点并收集自身及子孙节点
      }
      if (node.children) {
        const found = findNodeAndDescendantsById(node.children, id);
        if (found) {
          return found; // 在子节点中找到目标节点并收集自身及子孙节点
        }
      }
    }
    return null; // 如果未找到目标节点，返回 null
  }

  function collectDescendants(node) {
    const result = [node];
    if (node.children) {
      for (const child of node.children) {
        result.push(...collectDescendants(child)); // 递归收集子孙节点
      }
    }
    return result;
  }

  // 使用示例
  const nodeId = "1-1"; // 你要查找的节点 ID
  const result = findNodeAndDescendantsById(treeData, nodeId);
  console.log(result);

  // 示例：切换节点展开/关闭状态
  function toggleNode(treeData, id) {
    for (const node of treeData) {
      if (node.id === id) {
        node.open = !node.open; // 切换当前节点的展开/关闭状态
        toggleDescendants(node, node.open); // 递归切换所有子孙节点的状态
        return;
      }
      if (node.children) {
        toggleNode(node.children, id); // 递归查找并切换子节点状态
      }
    }
  }

  function toggleDescendants(node, open) {
    if (node.children) {
      for (const child of node.children) {
        child.open = open; // 设置子节点的状态为与父节点相同
        toggleDescendants(child, open); // 递归设置所有子孙节点的状态
      }
    }
  }

  // 使用示例
  const nodeId2 = "1"; // 要切换的节点 ID
  toggleNode(treeData, nodeId);
  console.log(treeData);
</script>
